var protocalTypes = {
		CS_ADD:1,
		SC_ADD:2,
		CS_SUB:3,
		SC_SUB:4,
		CS_MUL:5,
		SC_MUL:6,
		CS_DIV:7,
		SC_DIV:8
};
function Connection(host,port,handler){
	this.ip = host;
	this.port = port;
	this.socket = new WebSocket("ws://"+ host + ":" + port+"/dinner");
	this.socket.onmessage = function(event) { handler.process(event.data); };
	this.socket.onopen = function(event) { };
	this.socket.onclose = function(event) { };
}

Connection.prototype.send = function(message) {
	var stream = $.toJSON({type:message.type,data:message.write()});
	this.socket.send(stream);
}

function GlobalHandler() {
	this.protocals = new Map(100);
	this.handlers = new Map(100);
	this.dummyHandler = new DummyHandler();
}
GlobalHandler.prototype.register = function(protocalType,ProtocalClazz,handler) {
	this.protocals.put(protocalType, ProtocalClazz);
	this.handlers.put(protocalType, handler);
}
GlobalHandler.prototype.getProtocal = function(protocalType) {
	return this.protocals.get(protocalType);
}
GlobalHandler.prototype.getHandler = function(protocalType) {
	var handler = this.handlers.get(protocalType);
	if(handler) {
		return handler;
	}
	return dummyHandler;
}
GlobalHandler.prototype.process = function(rawmsg) {
	var jraw = eval('('+rawmsg+')');
	var protocalClazz = this.protocals.get(jraw.type);
	var handler = this.handlers.get(jraw.type);
	if(protocalClazz) {
		var protocal = new protocalClazz;
		protocal.read(jraw.data);
		handler.process(protocal);
	}
}

function BaseHandler() {
	
}
BaseHandler.prototype.process = function() {}

function DummyHandler() {
	BaseHandler.call(this);
}
DummyHandler.prototype = new BaseHandler();
DummyHandler.prototype.constuctor = DummyHandler;
DummyHandler.prototype.process = new function(){}

function BaseProtocal() {
	this.type;
}
BaseProtocal.prototype.read = function(data) {}
BaseProtocal.prototype.write = function(){return null;}

